package com.only4play.session;

import com.only4play.auth.AuthenticatedUser;
import com.only4play.constant.AppConstant;
import com.only4play.utils.CookieUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.util.Objects;

/**
 * @author liyuncong
 * @version 1.0
 * @file SessionManager
 * @brief session管理器
 * @details session管理器
 * @date 2023-11-19
 * <p>
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                     NAME               DESCRIPTION
 * 2023-11-19               liyuncong          Created
 */
@Component
public class SessionManager {

    @Autowired
    private AccessTokenManager accessTokenManager;
    @Autowired
    private TicketGrantingTicketManager ticketGrantingTicketManager;


    public String setUser(AuthenticatedUser<Void> authenticatedUser, HttpServletRequest request, HttpServletResponse response) {
        String tgt = getCookieTgt(request);
        if (StringUtils.isBlank(tgt)) {
            // cookie中没有，生成一个tgt
            tgt = ticketGrantingTicketManager.generate(authenticatedUser);
            // TGT存到cookie中，和CAS登录保存cookie中名称一致：TGC
            CookieUtils.addCookie(AppConstant.TGC, tgt, "/", request, response);
        } else if (Objects.isNull(ticketGrantingTicketManager.getAndRefresh(tgt))) {
            ticketGrantingTicketManager.create(tgt, authenticatedUser);
        } else {
            ticketGrantingTicketManager.set(tgt, authenticatedUser);
        }
        return tgt;
    }

    public String getTgt(HttpServletRequest request) {
        String tgt = getCookieTgt(request);
        if (StringUtils.isBlank(tgt) || Objects.isNull(ticketGrantingTicketManager.getAndRefresh(tgt))) {
            return null;
        }
        return tgt;
    }

    public String getCookieTgt(HttpServletRequest request) {
        return CookieUtils.getCookie(request, AppConstant.TGC);
    }

}

